<template>
  <view class="searchPosi" v-if="props.type == 'search'">
    <view class="searchInput">
      <!-- <u-search shape="square" :clearabled="true" :show-action="false"
				v-model="params.title" placeholder='请输入家居名称' @search="updateParams" @clear="updateParams"></u-search> -->
      <u-search
        shape="square"
        :clearabled="true"
        :show-action="false"
        v-model="params.title"
        placeholder="请输入家居名称"
        @tap="gotoSearch"
      ></u-search>
    </view>
  </view>
  <up-skeleton :loading="loading" rows="10" :animate="true">
    <view class="findCases">
      <!-- 筛选区域 -->
      <view
        class="screen"
        v-if="props.type == 'list'"
        :class="isFixed ? 'fixed' : ''"
        :style="{ top: top + 'rpx' }"
      >
        <view class="itemBox">
          <up-scroll-list :indicator="false" style="display: flex">
            <view
              v-for="(item, catIndex) in catList"
              :key="catIndex"
              class="itemSlide"
              @tap="select(item)"
              :class="catId == item.id ? 'activeItem' : ''"
            >
              {{ item.name }}
            </view>
          </up-scroll-list>
        </view>
      </view>

      <view
        class="showCatBox"
        :style="
          isFixed
            ? { 'margin-top': top + 120 + 100 + 'rpx' }
            : { 'margin-top': 0 + 'rpx' }
        "
      >
        <view class="catContainer">
          <view
            v-for="(item, catIndex1) in catList1"
            :key="catIndex1"
            class="itemSlide"
            @tap="selectItem(item)"
          >
            <img :src="item.img" alt="" class="img" />
            <text class="name">{{ item.name }}</text>
          </view>
        </view>
      </view>
      <!-- 列表 -->
      <!-- 没有数据且未加载时的提示 -->
      <view class="nullData" v-if="arrList.length == 0 && !isLoading">
        <image
          src="https://img.zhizhuangtong.com/project_media/img/xcx/null.png"
          mode=""
          :class="props.type == 'search' ? 'addTop' : ''"
        ></image>
        <text>暂无数据</text>
      </view>

      <!-- 数据列表 -->
      <view class="list" v-else>
        <view class="warter" :class="props.type == 'search' ? 'addTop' : ''">
          <view class="waterfall-column">
            <view class="card" v-for="(item, index) in leftList" :key="index">
              <view
                class="row"
                @click.prevent="onDetails(item.id, item.sku[0].id)"
              >
                <up-lazy-load
                  :image="item.sku[0].img"
                  class="cover"
                  img-mode="aspectFit"
                ></up-lazy-load>
                <view class="title">
                  <text class="tig" v-if="item.sku[0].subsidy?.activity_id"
                    >平台补贴</text
                  ><text class="ccc">{{ item.title }}</text>
                </view>
                <view class="tag">
                  {{ item.sku[0].name }}
                </view>
                <!-- <view class="qvan">
									<text class="qvanItem" v-for="i in 4">满500减30</text>
								</view> -->
                <view class="bottomView">
                  <view
                    class="flex_row_btw_end"
                    v-if="!item.sku[0].subsidy?.activity_id"
                  >
                    <view class="unit">¥</view>
                    <view class="priceFlow">{{ item.sku[0].price.split('.')[0] }}</view>
                    <view class="priceHou" v-if="item.sku[0].price.includes('.')">.{{ item.sku[0].price.split('.')[1] }}</view>
                  </view>
                  <view
                    class="flex_row_btw_end"
                    v-if="item.sku[0].subsidy?.activity_id"
                  >
                    <view class="unit" style="color: #df3033">¥</view>
                    <!-- <view class="price" style="color: #df3033"
                      >{{ item.sku[0].subsidy?.price }}
                      </view
                    > -->
                    <view class="priceFlow" style="color: #df3033">{{ item.sku[0].subsidy.price.split('.')[0] }}</view>
                    <view class="priceHou" style="color: #df3033" v-if="item.sku[0].subsidy.price.includes('.')">.{{ item.sku[0].subsidy.price.split('.')[1] }}</view>
                    <text class="priceType">到手价</text>
                  </view>
                  <view v-if='item.sku[0].stock>0'
                    class="shopping"
                    @click.prevent="addCard(item.sku[0].id)"
                  >
                    <image
                      src="../../static/home/shopping@2x.png"
                      mode=""
                      class="img"
                    ></image>
                  </view>
                  <view v-else
                    class="shopping"
                    @click.prevent="addCardNo"
                  >
                    <image
                      src="../../static/home/shopping@2x.png"
                      mode=""
                      class="img"
                    ></image>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="waterfall-column">
            <view class="card" v-for="(item, index) in rightList" :key="index">
              <view
                class="row"
                @click.prevent="onDetails(item.id, item.sku[0].id)"
              >
                <up-lazy-load
                  :image="item.sku[0].img"
                  class="cover"
                  img-mode="aspectFit"
                ></up-lazy-load>
                <view class="title">
                  <text class="tig" v-if="item.sku[0].subsidy?.activity_id"
                    >平台补贴</text
                  ><text class="ccc">{{ item.title }}</text>
                </view>
                <view class="tag">
                  {{ item.sku[0].name }}
                </view>
                <!-- <view class="qvan">
									<text class="qvanItem" v-for="i in 4">满500减30</text>
								</view> -->
                <view class="bottomView">
                  <view
                    class="flex_row_btw_end"
                    v-if="!item.sku[0].subsidy?.activity_id"
                  >
                    <view class="unit">¥</view>
                    <view class="priceFlow">{{ item.sku[0].price.split('.')[0] }}</view>
                    <view class="priceHou" v-if="item.sku[0].price.includes('.')">.{{ item.sku[0].price.split('.')[1] }}</view>
                  </view>
                  <view
                    class="flex_row_btw_end"
                    v-if="item.sku[0].subsidy?.activity_id"
                  >
                    <view class="unit" style="color: #df3033">¥</view>
                    <view class="priceFlow" style="color: #df3033">{{ item.sku[0].subsidy.price.split('.')[0] }}</view>
                    <view class="priceHou" style="color: #df3033" v-if="item.sku[0].subsidy.price.includes('.')">.{{ item.sku[0].subsidy.price.split('.')[1] }}</view>
                    <text class="priceType">到手价</text>
                  </view>
                  <view v-if='item.sku[0].stock>0'
                    class="shopping"
                    @click.prevent="addCard(item.sku[0].id)"
                  >
                    <image
                      src="../../static/home/shopping@2x.png"
                      mode=""
                      class="img"
                    ></image>
                  </view>
                  <view v-else
                    class="shopping"
                    @click.prevent="addCardNo"
                  >
                    <image
                      src="../../static/home/shopping@2x.png"
                      mode=""
                      class="img"
                    ></image>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view v-if="isLoading" class="load-more-box">
          <text>加载中...</text>
        </view>

        <view v-if="!isLoading && !hasMoreData" class="load-more-box">
          <text>已经到底了</text>
        </view>
      </view>
    </view>
  </up-skeleton>
</template>

<script setup>
import { checkLogin } from "@/utils/auth.js";
import { listData, addCar, getOneLevelCat } from "@/api/homeFurnishings.js";
import { ref, onMounted, defineExpose, defineProps, watch } from "vue";
// 数据列表、加载状态和分页参数
const arrList = ref([]);
const hasMoreData = ref(true); // 初始化为true，表示还有更多数据
const props = defineProps({
  type: String,
  title: String,
  isFixed: Boolean,
  top: String,
  catId: String,
});
const params = ref({
  title: "",
  page: 1,
  cat_id: "",
  page_size: 20,
});

const refresherTriggered = ref(false); // 初始化为false，触发下拉刷新
const isLoading = ref(false); // 加载状态

// 初始化数据
onMounted(async () => {
  if (props.type == "search") {
    console.log("11111");
    params.value.title = props.title || "";
    params.value.cat_id = props.catId || "";
    queryList();
  } else {
    getLevelCat(0, "1");
    params.value.title = "";
    console.log("获取的分类id", catId.value);
  }
});

const updateParams = () => {
  params.value.page = 1;
  arrList.value = [];
  queryList();
};
const loading = ref(true);
// 添加瀑布流数据列表
const leftList = ref([]);
const rightList = ref([]); // 初始化数据
// 请求数据列表
const queryList = async () => {
  isLoading.value = true; // 设置加载中
  try {
    console.log("搜索数据", params.value, props.catId);
    let obj = {
      ...params.value,
    };
    if (props.catId != "" && props.catId != "99999") {
      obj.title = "";
    } else if (props.catId == "99999") {
      obj.cat_id = "";
    }
    console.log("xin", obj);
    const res = await listData(obj);
    if (res.code === 1) {
      if (params.value.page === 1) {
        // 重置两列数据
        leftList.value = [];
        rightList.value = [];
        arrList.value = [];
      }
      // 处理新数据
      res.data.list.forEach((item, index) => {
        if (index % 2 === 0) {
          leftList.value.push(item);
        } else {
          rightList.value.push(item);
        }
      });

      // 更新原有数组(保持兼容)
      arrList.value = [...leftList.value, ...rightList.value];

      // 判断是否还有更多数据
      hasMoreData.value = res.data.list.length >= params.value.page_size;
      params.value.page += 1;
    }
    loading.value = false;
    setTimeout(() => {
      isLoading.value = false;
    }, 500);
  } catch (error) {
    console.error("请求数据失败:", error);
  } finally {
    isLoading.value = false; // 加载完成
  }
};

// 重置查询条件并重新加载数据
const update = () => {
  params.value.title = "";
  params.value.catId = "";
  params.value.page = 1;
  queryList();
};
const updateHasQuery = () => {
  params.value.page = 1;
  queryList();
};

const queryLists = (obj) => {
  params.value = {
    ...obj,
  };
  queryList();
};

// 去详情
const onDetails = (id, skuId) => {
  uni.navigateTo({
    url: "/pages/find/homeFurnish/index?id=" + id + "&skuId=" + skuId,
  });
};
//加入购物车
const addCard = async (id) => {
  if (!checkLogin()) {
    return;
  } 
  let goods = [
    {
      sku_id: id,
      num: 1,
    },
  ];
  const res = await addCar({
    goods: JSON.stringify(goods),
  });
  if (res.code === 1) {
    wx.showToast({
      title: res.msg,
      icon: "none",
      duration: 2000,
    });
  }
};
const addCardNo = () => {
  wx.showToast({
    title: "暂时无货，已告知商家尽快补货，请稍后再试！",
    icon: "none",
    duration: 2000,
  });
};
//查询
const gotoSearch = () => {
  uni.navigateTo({
    url: "/pages/find/homeFurnishSearchHistory/index",
  });
};

const showCat = ref(false);
const catId = ref("");
//选择一级分类
const select = (item) => {
  getLevelCat(item.id, "2");
  catId.value = item.id;
  params.value.cat_id = catId.value;
  params.value.page = 1;
  queryList();
  showCat.value = true;

  if (props.isFixed) {
    uni.pageScrollTo({
      scrollTop: 128, // 滚动到目标元素的顶部
      duration: 10, // 滚动动画时长，单位ms
    });
  }
};
//点击二级分类
const selectItem = (item) => {
  uni.navigateTo({
    url:
      "/pages/find/homeFurnishSearch/index?title=" +
      item.name +
      "&catId=" +
      item.id,
  });
};
const catList = ref([]);
const catList1 = ref([]);
//加入购物车
const getLevelCat = async (id, level) => {
  const res = await getOneLevelCat({
    pid: id,
  });
  if (res.code === 1) {
    // 递归获取所有 childlist 的组合
    // const getAllChildLists = (tree) => {
    // 	return tree.reduce((acc, item) => {
    // 		if (item.childlist && item.childlist.length > 0) {
    // 			acc.push(...item.childlist);
    // 			// 递归处理子分类
    // 			acc.push(...getAllChildLists(item.childlist));
    // 		}
    // 		return acc;
    // 	}, []);
    // };
    // catList.value = getAllChildLists(res.data.tree);
    //一级组合
    // catList.value = res.data.tree.reduce((acc, item) => {
    // 	if (item.childlist && item.childlist.length > 0) {
    // 		acc.push(...item.childlist);
    // 	}
    // 	return acc;
    // }, []);
    // 获取第二级的 childlist 组合
    // catList.value = res.data.tree.reduce((acc, item) => {
    // 	if (item.childlist && item.childlist.length > 0) {
    // 		// 遍历第一级的 childlist
    // 		item.childlist.forEach(child => {
    // 			if (child.childlist && child.childlist.length > 0) {
    // 				// 将第二级的 childlist 加入结果
    // 				acc.push(...child.childlist);
    // 			}
    // 		});
    // 	}
    // 	return acc;
    // }, []);

    if (level == 1) {
      catList.value = res.data.list.sort((a, b) => {
        if (a.name === "家具") return -1;
        if (b.name === "家具") return 1;
        return 0;
      });
      catId.value = catList.value[0].id;
      getLevelCat(catId.value, "2");
      params.value.cat_id = catId.value;
      await queryList();
    } else {
      catList1.value = res.data.list;
    }

    console.log(catList.value);
  }
};
// 对外暴露方法
defineExpose({
  queryList,
  params,
  update,
  hasMoreData,
  updateHasQuery,
  queryLists,
});
</script>

<style scoped lang="less">
.priceType {
  min-width: 70rpx;
  flex: 1;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 24rpx;
  color: #df3033;
  line-height: 36rpx;
  text-align: left;
  font-style: normal;
  text-transform: none;
  margin-left: 8rpx;
  height:34rpx;
}
.fixed {
  position: fixed !important;
  left: 0 !important;
  width: 100% !important;
  z-index: 999 !important;
  background-color: #fff;
}

.showCatBox {
  background-color: #fff;
  width: calc(100% - 70rpx);
  margin: 0 auto;
  padding: 40rpx 8rpx;
  border-radius: 16rpx;

  .catContainer {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    row-gap: 36rpx;

    .itemSlide {
      width: 20%;
      display: flex;
      flex-direction: column;
      align-items: center;

      .img {
        width: 88rpx;
        height: 88rpx;
        border-radius: 0rpx 0rpx 0rpx 0rpx;
      }

      .name {
        font-weight: 400;
        font-size: 24rpx;
        color: #666666;
        margin-top: 10rpx;
        text-align: center;
      }
    }
  }
}

.searchPosi {
  position: fixed;
  z-index: 999999;
  background-color: #fff;
  width: 100%;
  justify-content: center;
  height: 118rpx;
  display: flex;
  align-items: center;
  top: 0;

  .searchInput {
    width: calc(100% - 60rpx);
  }
}

.itemBox {
  width: calc(100% - 60rpx);
  height: 100rpx;
  margin: 0 auto;

  .itemSlide {
    flex: 1;
    white-space: nowrap; // 防止文字换行
    padding-right: 50rpx;
    font-weight: 400;
    font-size: 30rpx;
    height: 100rpx;
    color: #333333;
    max-width: 140rpx;
    text-align: left;
    line-height: 100rpx;
  }

  .itemSlide:nth-last-of-type(1) {
    padding-right: 0rpx;
  }

  .activeItem {
    height: 100rpx;
    font-weight: 600;
    font-size: 34rpx;
    color: #ff8b41;
    line-height: 100rpx;
  }
}

.findCases {
  width: 100%;
  height: 100%;

  .screen {
    width: 100%;
    display: flex;
    align-items: center;

    .search {
      width: calc(100% - 40px);
      padding: 50rpx 1px 0;
      margin-left: 40rpx;
    }
  }

  .nullData {
    height: calc(100% - 110rpx);
  }

  .list {
    width: 100%;
    padding: 4rpx 23rpx 0;
    box-sizing: border-box;

    .warter {
      display: flex;
      justify-content: space-between;
      width: 100%;

      .waterfall-column {
        width: 50%;
      }

      .card {
        display: flex;
        padding: 20rpx 7rpx 0rpx;
        // margin-bottom: 25rpx;
        // background-color: #fff;
        border-radius: 16rpx;
        box-sizing: border-box;
        width: 100%;

        .row {
          border-radius: 16rpx;
          box-sizing: border-box;
          width: 100%;
          background-color: #fff;
          // box-shadow: 0rpx 8rpx 40rpx 0rpx rgba(0, 0, 0, 0.05);
          display: block;

          .cover {
            width: 100%;
            display: block;
            background-color: #fff;

            ::v-deep(.u-lazy-item) {
              overflow: hidden;
              box-sizing: border-box;
              border-top-left-radius: 16rpx;
              border-top-right-radius: 16rpx;

              image {
                height: 342.5rpx !important;
                border-top-left-radius: 16rpx;
                border-top-right-radius: 16rpx;
                object-fit: cover !important;
                box-sizing: border-box;
                background-color: #fff;
              }
            }
          }

          ::v-deep(.u-wrap) {
            width: 100%;
            height: 100%;
          }

          .title {
            width: 90%;
            height: 50rpx;
            margin-top: 5rpx;
            letter-spacing: 0.5px;
            font-family: PingFang SC, PingFang SC;
            font-weight: 500;
            font-size: 28rpx;
            color: #333333;
            line-height: 50rpx;
            text-align: left;
            font-style: normal;
            text-transform: none;

            margin-left: 16rpx;

            display: flex;
            align-items: center;

            .tig {
              font-weight: 400;

              font-size: 22rpx;
              color: #ffffff;
              width: 100rpx;
              display: inline-block;
              height: 34rpx;
              text-align: center;
              line-height: 34rpx;
              background: linear-gradient(90deg, #fc585b 0%, #ee3939 100%);
              border-radius: 4rpx 4rpx 4rpx 4rpx;
              margin-right: 4rpx;
            }

            .ccc {
              width: calc(100% - 100rpx);
              text-overflow: ellipsis;
              flex-wrap: nowrap;
              white-space: nowrap;
              overflow: hidden;
            }

            /* 显示省略号 */
          }

          .qvan {
            margin-top: 25rpx;
            margin-bottom: 20rpx;
            width: 90%;
            display: flex;
            flex-direction: row;
            column-gap: 6rpx;
            align-items: center;
            margin-left: 10px;
            overflow-y: auto;

            .qvanItem {
              flex: 1;
              height: 30rpx;
              font-family: PingFang SC, PingFang SC;
              font-weight: 400;
              font-size: 22rpx;
              color: #ff3e3e;
              line-height: 30rpx;
              padding: 0 7rpx;
              background: rgba(255, 255, 255, 0.4);
              border-radius: 4rpx 4rpx 4rpx 4rpx;
              border: 1rpx solid #ff8383;
              white-space: nowrap;
              /* 新增：防止文字换行 */
              flex-shrink: 0;
              /* 新增：防止子元素缩小 */
            }
          }

          .tag {
            margin-left: 16rpx;
            width: 90%;
            display: flex;
            margin-top: 5rpx;
            // height: 60rpx;
            // padding: 0 4rpx;
            display: flex;
            align-items: center;
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 24rpx;
            color: #7a7a7a;
            line-height: 30rpx;
            text-align: left;
            font-style: normal;
            text-transform: none;
            display: -webkit-box;
            /* 必须结合WebKit浏览器 */
            -webkit-line-clamp: 2;
            /* 限制显示的行数 */
            -webkit-box-orient: vertical;
            /* 垂直排列盒子 */
            overflow: hidden;
            /* 隐藏超出部分 */
            text-overflow: ellipsis;
            /* 显示省略号 */
          }

          .bottomView {
            margin-left: 16rpx;
            margin-right: 16rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 90%;
            padding-bottom: 25rpx;
            margin-top: 10rpx;
            height:34rpx;
            .unit {
              font-weight: 500;
              font-size: 24rpx;
              color: #333333;
              height:32.5rpx;
            }

            .price {
              font-weight: 500;
              font-size: 30rpx;
              color: #333333;
            }

            .shopping {
              width: 45rpx;
              height: 45rpx;

              .img {
                width: 45rpx;
                height: 45rpx;
              }
            }
          }
        }
      }
    }
  }

  .load-more-box {
    text-align: center;
    width: 100%;
    padding-top: 20rpx;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    color: #7a7a7a;
  }
}

.addTop {
  margin-top: 40rpx;
}
</style>
